﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace kim.Common
{
    /// <summary>
    /// 文件和图片操作类
    /// 文件的保存路径请配置Web.config“WaterPmarkicPath”水印图地址
    /// </summary>
    public class PubFileAndImageFunc
    {
        #region 通过Web.config的key找到Value ----路径
        /// <summary>
        /// 通过Web.config的key找到Value ----路径
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>Value</returns>
        public static string getWebconfigValuebyKey(string key)
        {
            string Path = string.Empty;
            try
            {
                Path = System.Configuration.ConfigurationManager.AppSettings[key];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Path;
        }
        #endregion

        #region 根据格式数组来判断上传文件类型是否符合需求
        /// <summary>
        /// 根据格式数组来判断上传文件类型是否符合需求
        /// </summary>
        /// <param name="hifile">上传控件</param>
        /// <param name="arrExtension">格式数组表string[] arrExtension =   { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };</param>
        /// <returns>false表示不匹配格式，true表示匹配格式</returns>
        public static bool IsAllowedExtension(FileUpload hifile, string[] arrExtension)
        {
            bool temp = false;
            string strOldFilePath = "", strExtension = "";
            if (arrExtension != null)
            {
                if (hifile.PostedFile.FileName != string.Empty)
                {
                    strOldFilePath = hifile.PostedFile.FileName;
                    strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                    for (int i = 0; i < arrExtension.Length; i++)
                    {
                        if (strExtension.Equals(arrExtension[i]))
                        {
                            temp = true;//有限制格式
                        }
                    }
                }
            }
            else
            {
                temp = true;//未限定文件格式—可上传任意文件
            }
            return temp;
        }
        #endregion

        /// <summary>
        /// 从一句字串中提取前多少个字母
        /// </summary>
        /// <param name="str"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        /// <summary>
        /// 返回一个由时间和随机数组成的字符串
        /// </summary>
        /// <returns></returns>
        public static string daterodom()
        {
            DateTime now = DateTime.Now;
            string newname = now.ToString("yyyyMMddhhmmss");
            Random a = new Random();
            int s = Convert.ToInt32(a.NextDouble() * 100000 + 100000);
            return newname + s.ToString();
        }
        /// <summary>
        /// 文件删除
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static bool DelFile(string path)
        {
            File.Delete(path);

            if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 上传图片
        /// </summary> 二〇一二年十月十六日 11:31:39
        /// <param name="fileupload"></param>
        /// <param name="path"></param>
        public static string fileuploadcode(FileUpload fileupload, string path)
        {

            if (fileupload.HasFile)
            {
                //上传图片
                //取出文件路径
                string FileFullName = fileupload.PostedFile.FileName;
                //取出文件名
                string FileName = FileFullName.Substring(FileFullName.LastIndexOf("\\") + 1);
                //取出文件类型
                string FileType = FileFullName.Substring(FileFullName.LastIndexOf(".") + 1);

                string pdate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();

                string newpath = "";

                if (Directory.Exists(HttpContext.Current.Server.MapPath(path + pdate)) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path + pdate));
                }

                newpath = path + pdate + "/";

                string newfilename = daterodom();
                //获取文件要存的路径
                string SavePath = HttpContext.Current.Server.MapPath(newpath) + newfilename + "." + FileType;

                string ReturnPath = newpath + newfilename + "." + FileType;

                FileType = FileType.ToLower();

                if (FileType == "jpg" || FileType == "bmp" || FileType == "gif" || FileType == "png")
                {
                    //保存路径
                    fileupload.PostedFile.SaveAs(SavePath);

                    return ReturnPath;
                }
                else
                {
                    HttpContext.Current.Response.Write("<script language='javascript'>alert('对不起,图片格式错误');</script>");

                    HttpContext.Current.Response.End();

                    return "No";
                }
            }
            else
            {
                return "";
            }
        }


        #region 保存大图、缩略图
        /// <summary>
        /// 保存大图、缩略图
        /// </summary>
        /// <param name="FileUpload1">上传控件</param>
        /// <param name="BigDirectory">大图图片文件夹</param>
        /// <param name="Watermark">是否打水印bool：true表示打水印 false表示不打水印</param>
        /// <param name="ThumbWidth">缩略图的宽度</param>
        /// 修改作者：金成 
        /// <returns>图片保存的路径</returns>
        public static void DrawImage(FileUpload FileUpload1, string BigDirectory, bool Watermark, int ThumbWidth, out string ReturnPath, out string ReturnMinPath)
        {
            ReturnPath = "";
            ReturnMinPath = "";
            if (FileUpload1.HasFile)
            {
                //文件夹不存在，自动建立
                string pdate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();

                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(BigDirectory + pdate)))
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(BigDirectory + pdate));

                //组合保存全路径
                string newpath = BigDirectory + pdate + "/";
                string Filepath = FileUpload1.PostedFile.FileName;//取全路径
                string Filename_last = Filepath.Substring(Filepath.LastIndexOf(".") + 1);//取文件后缀名
                string RandomFileName = AppConfigBLL.RandomFileName;
                Filename_last = Filename_last.ToLower();
                string FullSavePath = HttpContext.Current.Server.MapPath(newpath) + RandomFileName + "." + Filename_last;

                try
                {
                    //取上传控件的图片 用于取图片大小 
                    //必须用System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
                    System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

                    #region 大图
                    //当需要水印时 -----图片水印
                    if (Watermark == true && Filename_last.ToLower() != "gif")
                    {
                        //定义水印图片的画板
                        string WaterPmarkicPath = HttpContext.Current.Server.MapPath(getWebconfigValuebyKey("WaterPmarkicPath"));
                        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(WaterPmarkicPath);
                        //仅当大图的宽度和高度都比水印图片大的时候
                        if ((image.Width > copyImage.Width) && (image.Height > copyImage.Height))
                        {
                            //将水印画入大图
                            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
                            g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
                            g.Dispose();
                            //保存加水印的大图
                            image.Save(FullSavePath);
                        }
                        else//仅当大图的宽度和高度都比水印图片小的时候直接保存图片
                        {
                            if (Filename_last == "jpg" || Filename_last == "bmp" || Filename_last == "gif" || Filename_last == "png")
                            {
                                //保存路径
                                FileUpload1.PostedFile.SaveAs(FullSavePath);
                                ReturnPath = newpath + RandomFileName + "." + Filename_last;
                                ReturnMinPath = ReturnPath.Replace("img", "thumb");

                            }
                            else
                            {
                                HttpContext.Current.Response.Write("<script language='javascript'>alert('对不起,图片格式错误');</script>");
                                HttpContext.Current.Response.End();

                            }
                        }
                        //释放画笔
                        copyImage.Dispose();
                    }
                    else//不打水印
                    {
                        if (Filename_last == "jpg" || Filename_last == "bmp" || Filename_last == "gif" || Filename_last == "png")
                        {
                            //保存路径
                            FileUpload1.PostedFile.SaveAs(FullSavePath);
                            ReturnPath = newpath + RandomFileName + "." + Filename_last;
                            ReturnMinPath = ReturnPath.Replace("img", "thumb");

                        }
                        else
                        {
                            HttpContext.Current.Response.Write("<script language='javascript'>alert('对不起,图片格式错误');</script>");
                            HttpContext.Current.Response.End();

                        }


                    }

                    #endregion


                    #region 缩略图
                    //判断是否保存缩略图,ThumbWidth为0时不添加缩略图
                    if (ThumbWidth != 0)
                    {
                        //文件夹不存在，自动建立
                        if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(BigDirectory + pdate).Replace("img", "thumb")))
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(BigDirectory + pdate).Replace("img", "thumb"));

                        string ThumbImagePath = FullSavePath.Replace("img", "thumb");
                        //当上传图片大于缩略图的Width时
                        if (image.Width > ThumbWidth)
                        {
                            int ThumbHeight = (ThumbWidth * image.Height) / image.Width;
                            System.Drawing.Image img = image.GetThumbnailImage(ThumbWidth, ThumbHeight, null, IntPtr.Zero);
                            //保存普通缩略图
                            img.Save(ThumbImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            //img.Dispose();
                        }
                        else
                        {
                            image.Save(ThumbImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    #endregion

                    //释放图片对象Drawing.Image;
                    image.Dispose();

                    //ReturnPath = ReturnPath.Replace("img", "thumb") ;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


        public static string DrawImageforNews(FileUpload FileUpload1, string BigDirectory, bool Watermark, int ThumbWidth)
        {
            //文件夹不存在，自动建立
            if (!System.IO.Directory.Exists(BigDirectory))
                System.IO.Directory.CreateDirectory(BigDirectory);

            //组合保存全路径
            string Filepath = FileUpload1.PostedFile.FileName;//取全路径
            string Filename_last = Filepath.Substring(Filepath.LastIndexOf(".") + 1);//取文件后缀名
            string FullSavePath = BigDirectory + AppConfigBLL.RandomFileName + "." + Filename_last;
            try
            {
                //取上传控件的图片 用于取图片大小 
                //必须用System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
                System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

                #region 大图
                //当需要水印时 -----图片水印
                if (Watermark == true && Filename_last.ToLower() != "gif")
                {
                    //定义水印图片的画板
                    System.Drawing.Image copyImage = System.Drawing.Image.FromFile(getWebconfigValuebyKey("WaterPmarkicPathfornews"));
                    //仅当大图的宽度和高度都比水印图片大的时候
                    if ((image.Width > copyImage.Width) && (image.Height > copyImage.Height))
                    {
                        //将水印画入大图
                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
                        g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
                        g.Dispose();
                        //保存加水印的大图
                        image.Save(FullSavePath);
                    }
                    else//仅当大图的宽度和高度都比水印图片小的时候直接保存图片
                    {
                        FileUpload1.PostedFile.SaveAs(FullSavePath);
                    }
                    //释放画笔
                    copyImage.Dispose();
                }
                else//不打水印
                {
                    FileUpload1.PostedFile.SaveAs(FullSavePath);
                }
                #endregion

                #region 缩略图
                //判断是否保存缩略图,ThumbWidth为0时不添加缩略图
                if (ThumbWidth != 0)
                {
                    //文件夹不存在，自动建立
                    if (!System.IO.Directory.Exists(BigDirectory.Replace("img", "thumb")))
                        System.IO.Directory.CreateDirectory(BigDirectory.Replace("img", "thumb"));

                    string ThumbImagePath = FullSavePath.Replace("img", "thumb");
                    //当上传图片大于缩略图的Width时
                    if (image.Width > ThumbWidth)
                    {
                        int ThumbHeight = (ThumbWidth * image.Height) / image.Width;
                        System.Drawing.Image img = image.GetThumbnailImage(ThumbWidth, ThumbHeight, null, IntPtr.Zero);
                        //保存普通缩略图
                        img.Save(ThumbImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        img.Dispose();
                    }
                    else
                    {
                        image.Save(ThumbImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
                #endregion

                //释放图片对象Drawing.Image;
                image.Dispose();
                return FullSavePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 重设图片大小（只保存重画图片）

        /// <summary>
        /// 重设图片大小（只保存重画图片）
        /// </summary>
        /// <param name="FileUpload1"></param>
        /// <param name="BigDirectory"></param>
        /// <param name="MaxWidth">最大宽度</param>
        /// <param name="MaxHeight">最大高度</param>
        /// <returns></returns>
        public static string Upload_BuildDrawImage(FileUpload FileUpload1, string BigDirectory, int MaxWidth, int MaxHeight)
        {
            //文件夹不存在，自动建立
            if (!System.IO.Directory.Exists(BigDirectory))
                System.IO.Directory.CreateDirectory(BigDirectory);

            //组合保存全路径
            string Filepath = FileUpload1.PostedFile.FileName;//取全路径
            string Filename_last = Filepath.Substring(Filepath.LastIndexOf(".") + 1);//取文件后缀名
            string FullSavePath = BigDirectory + AppConfigBLL.RandomFileName + "." + Filename_last;
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
                int oWidth = image.Width;
                int oHeight = image.Height;
                if (oWidth <= MaxWidth)
                {
                    if (MaxHeight > 0 && oHeight > MaxHeight)
                    {
                        oWidth = Convert.ToInt32((float)oWidth * ((float)MaxHeight / (float)oHeight));
                        oHeight = MaxHeight;
                    }
                }
                else
                {
                    oHeight = Convert.ToInt32((float)oHeight * ((float)MaxWidth / (float)oWidth));
                    oWidth = MaxWidth;
                    if (MaxHeight > 0 && oHeight > MaxHeight)
                    {
                        oWidth = Convert.ToInt32((float)oWidth * ((float)MaxHeight / (float)oHeight));
                        oHeight = MaxHeight;
                    }
                }

                System.Drawing.Image myThumbnail = image.GetThumbnailImage(oWidth, oHeight, null, IntPtr.Zero);
                myThumbnail.Save(FullSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                image.Dispose();
                myThumbnail.Dispose();
                return FullSavePath;
            }
            catch (Exception ex) { throw ex; }
        }

        #endregion



        public static string fileuploadcoderar(FileUpload fileupload, string path)
        {

            if (fileupload.HasFile)
            {
                //上传图片
                //取出文件路径
                string FileFullName = fileupload.PostedFile.FileName;
                //取出文件名
                string FileName = FileFullName.Substring(FileFullName.LastIndexOf("\\") + 1);
                //取出文件类型
                string FileType = FileFullName.Substring(FileFullName.LastIndexOf(".") + 1);

                string pdate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();

                string newpath = "";

                if (Directory.Exists(HttpContext.Current.Server.MapPath(path + pdate)) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path + pdate));
                }

                newpath = path + pdate + "/";

                string newfilename = daterodom();
                //获取文件要存的路径
                string SavePath = HttpContext.Current.Server.MapPath(newpath) + newfilename + "." + FileType;

                string ReturnPath = newpath + newfilename + "." + FileType;

                FileType = FileType.ToLower();

                if (FileType == "doc" || FileType == "docx" || FileType == "wps" || FileType == "pdf" || FileType == "rar" ||FileType == "zip")
                {
                    //保存路径
                    fileupload.PostedFile.SaveAs(SavePath);

                    return ReturnPath;
                }
                else
                {
                    HttpContext.Current.Response.Write("<script language='javascript'>alert('对不起,只能上传 doc docx wps pdf rar zip 格式的文件');</script>");

                    HttpContext.Current.Response.End();

                    return "No";
                }
            }
            else
            {
                return "";
            }
        }


    }
}